import {AfterViewChecked, Component, Input, OnInit, ViewChild} from '@angular/core';
import {EntityService} from '../../shared/services/entity.service';
import {IPDialog} from '../../shared/model/share.model';
import {NgForm} from '@angular/forms';
import {FormValidate} from '../../shared/model/page-config.model';

@Component({
  templateUrl: './function-add-edit.component.html',
  styles: [`
    ul{ padding: 0px; margin: 0px; }
  `]
})
export class FunctionAddEditComponent implements OnInit, AfterViewChecked {

  dictionaries: any;
  @Input() dialog: IPDialog;
  @ViewChild('dialogForm') currentForm: NgForm;
  dialogForm: NgForm;
  model: any;
  config: any;
  cols: any;
  validates: any;
  constructor(
    private service: EntityService
  ) {}
  ngOnInit() {
    this.model = this.dialog.data.inData;
    if (!this.model) {
      this.model = {};
    }
    this.config = this.service.pageData.dialog;
    // this.cols = this.config.cols;
    this.validates = new FormValidate(this.config.cols);
    this.cols = this.validates.column;
    console.log(this.cols);
    console.log(this.validates);
  }
  get colsMust(){
    let res = {};
    Object.keys(this.cols).forEach(field => {
      if ( this.cols[field].validates ) {
        res[field] = typeof this.cols[field].validates.required !== 'undefined' ? true : false;
      }
    });
    return res;
  }
  get colsWarning(){
    let res = {};
    Object.keys(this.validates.formError).forEach(field => {
        res[field] = this.validates.formError[field] ? true : false;
    });
    return res;
  }

  formChanged() {
    if (this.currentForm === this.dialogForm) {return; }
    this.dialogForm = this.currentForm;
    if (this.dialogForm) {
      this.dialogForm.valueChanges
        .subscribe(data => {
          this.onValueChanged(data);
        });
    }
  }

  onValueChanged(data?: any, isValidateAll?: boolean) {
    if (!this.dialogForm) {return; }
    const form = this.dialogForm.form;
    if (this.validates && this.validates.formError) {
      Object.keys(this.validates.formError).forEach(field => {
        // 清除当前错误信息
        this.validates.formError[field] = '';
        const control = form.get(field);
        // isValidateAll:是点击保存时验证
        // control.dirty:在输入框中编写时验证
        if (control && ( isValidateAll ||  control.dirty )) {
          const  messages = this.validates.vMessages[field]; // this.validationMessages[field];
          if (control.errors) {
            Object.keys(control.errors).forEach(key => {
              this.validates.formError[field] += `${messages[key]} `;
            });
          }
        }
      });
    }
  }

  getValudateMsg(field) {
    if (this.config) {
      let pro = this.config.property[field];
      return `[${pro.title}] ${pro.validateMsg.required}`;
    }
    return '';
  }

  ngAfterViewChecked() {
    this.formChanged();
  }
}
